package com.java.interview.加密解密;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;

/**
 * @author Administrator
 */
public class AES {
    private static Cipher mDecryptCipher;

    // 加密
    public static byte[] Encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        mDecryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
        mDecryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(sKey.getBytes()));
        byte[] encrypted = mDecryptCipher.doFinal(sSrc.getBytes("utf-8"));
        OutputStream out = new FileOutputStream("F:/test/lbdemo");
        InputStream is = new ByteArrayInputStream(encrypted);
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = is.read(buff)) != -1) {
            out.write(buff, 0, len);
        }
        is.close();
        out.close();
        return encrypted;//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    // 解密
    public static String Decrypt(String sKey)  {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(sKey.getBytes()));
            InputStream is = new FileInputStream("F:/test/lbdemo");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int t = 0;
            while ((t = is.read(buffer)) >= 0) {
                bos.write(buffer, 0, t);
                bos.flush();
            }
            byte[] encrypted1 = bos.toByteArray();
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        /*
         * 此处使用AES-128-ECB加密模式，key需要为16位。
         */
        String cKey = "0123456789012345";
        // 需要加密的字串
        String cSrc = "[{\"id\":\"1\",\"name\":\"新告警\",\"description\":null},{\"id\":\"2\",\"name\":\"处理中\",\"description\":null},{\"id\":\"3\",\"name\":\"已处理\",\"description\":null}]";
        // 加密
        System.out.println("加密前的字串是：\n" + cSrc);
        byte[] enString = AES.Encrypt(cSrc, cKey);
        System.out.println("加密后的字串是：\n" + new String(enString));

        // 解密
        String DeString = AES.Decrypt(cKey);
        System.out.println("解密后的字串是：\n" + DeString);
    }
}

//源代码片段来自云代码http://yuncode.net